from itsdangerous import TimedJSONWebSignatureSerializer
from toutiao.settings import Config
from datetime import datetime, timedelta
from auth.auth_jwt import generic_token

#生成token
def get_user_token(user_id):

    # serializer=TimedJSONWebSignatureSerializer(secret_key=Config.SECRET_KEY,expires_in=3600)
    #
    # data = {
    #     'user_id':user_id
    # }
    #
    # return serializer.dumps(data).decode()

    """
    获取当前时间
    分别组织token和refresh_token的payload数据
           token和refresh_token的expiry时间
    生成token
    :param user_id:
    :return:
    """

    # 获取当前时间
    now = datetime.utcnow()
    # 分别组织token和refresh_token的payload数据
    token_payload = {'refresh':False, 'user_id':user_id}

    refresh_payload = {'refresh':True, 'user_id': user_id}

    # 分别组织token和refresh_token的expiry时间
    token_expiry = now + timedelta(hours=Config.JWT_EXPIRY_HOURS)

    refresh_expiry = now + timedelta(days=Config.JWT_REFRESH_DAYS)

    # 生成token
    # 两个小时有效期
    token = generic_token(token_payload, token_expiry)

    # 十四天有效期
    refresh_token = generic_token(refresh_payload, refresh_expiry)

    return token, refresh_token









